import React from 'react';
import { renderToString } from 'react-dom/server';
import { StaticRouter as Router } from 'react-router';
import { Provider, useStaticRendering } from 'mobx-react';
import { toJS } from 'mobx';
import stores from '@/store/webStore';
import App from '@/shared_web';

// useStaticRendering(true);
const stringify = (o) => {
	let cache = [];
	let data = JSON.stringify(o, function(key, value) {
		if (typeof value === 'object' && value !== null) {
			if (cache.indexOf(value) !== -1) {
				// Circular reference found, discard key
				return;
			}
			// Store value in our collection
			cache.push(value);
		}
		// console.log(value);
		return value;
	});
	cache = null;
	return data;
};
export const ssr = async(ctx, next) => {
	const context = {};
	const createHtml = renderToString(
		<Provider {...stores}>
			<Router location={ctx.path} context={context} >
				<App/>
			</Router>
		</Provider>
	);

	if (context.url) {
		ctx.redirect(context.url);
	} else {
		await ctx.render('web', {
			layout: false,
			content: createHtml,
			js: stringify(stores)
		});
	};
};

export default ssr;
